package com.evolution.warlock.common.controller;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.evolution.warlock.entity.CriminalBase;
import com.evolution.warlock.excle.ExcelConfiguration;

@Controller
public class ExportExcelController {
	// 导出excel方法
	@RequestMapping("viewExcel")
	public void viewExcel(HttpServletRequest request, HttpServletResponse response, Condition condition) {
		HttpSession session = request.getSession();
		session.setAttribute("state", null);
		// 生成提示信息，
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		String codedFileName = null;
		OutputStream fOut = null;
		try {
			response.setCharacterEncoding("UTF-8");

			String now = new SimpleDateFormat("yyyyMMdd-hhmmss").format(new Date());
			// 进行转码，使其支持中文文件名
			codedFileName = java.net.URLEncoder.encode("作案信息表" + now, "UTF-8");
			response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
			// response.addHeader("Content-Disposition",
			// "attachment;   filename=" + codedFileName + ".xls");
			// 产生工作簿对象
			HSSFWorkbook workbook = new HSSFWorkbook();
			// 产生工作表对象
			HSSFSheet sheet = workbook.createSheet();
			for (int i = 0; i <= 30000; i++) {
				HSSFRow row = sheet.createRow((int) i);// 创建一行
				HSSFCell cell = row.createCell((int) 0);// 创建一列
				cell.setCellType(HSSFCell.CELL_TYPE_STRING);
				cell.setCellValue("测试成功" + i);
			}
			fOut = response.getOutputStream();
			workbook.write(fOut);
		} catch (UnsupportedEncodingException e1) {
		} catch (Exception e) {
		} finally {
			try {
				fOut.flush();
				fOut.close();
			} catch (IOException e) {
			}
			session.setAttribute("state", "open");
		}
		System.out.println("文件生成...");
		System.out.println(condition + " name=" + condition.getName());
	}

	@RequestMapping("viewExcel2")
	public void viewExcel2(HttpServletRequest request, HttpServletResponse response, Condition condition) {
		HttpSession session = request.getSession();
		session.setAttribute("state", null);
		// 生成提示信息，
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		String codedFileName = null;
		OutputStream fOut = null;
		try {
			response.setCharacterEncoding("UTF-8");

			String now = new SimpleDateFormat("yyyyMMdd-hhmmss").format(new Date());
			// 进行转码，使其支持中文文件名
			codedFileName = java.net.URLEncoder.encode("作案信息表" + now, "UTF-8");
			response.setHeader("content-disposition", "attachment;filename=" + codedFileName + ".xls");
			// response.addHeader("Content-Disposition",
			// "attachment;   filename=" + codedFileName + ".xls");
			// 产生工作簿对象
			// 产生工作表对象
			List<CriminalBase> list = search(condition);
			// list=
			HSSFWorkbook workbook = createWorkbook(list);
			fOut = response.getOutputStream();
			workbook.write(fOut);
		} catch (UnsupportedEncodingException e1) {
		} catch (Exception e) {
		} finally {
			try {
				fOut.flush();
				fOut.close();
			} catch (IOException e) {
			}
			session.setAttribute("state", "open");
		}
		System.out.println("文件生成...");
		System.out.println(condition + " name=" + condition.getName());
	}

	static ExcelConfiguration formater = new ExcelConfiguration();

	private HSSFWorkbook createWorkbook(List<CriminalBase> list) throws IllegalArgumentException,
			IllegalAccessException {
		// TODO Auto-generated method stub
		// 声明一个工作薄
		HSSFWorkbook wb = new HSSFWorkbook();
		// 生成一个表格
		HSSFSheet st = wb.createSheet("作案信息");
		
		//
		

		HSSFCellStyle normalStyle = wb.createCellStyle();
		normalStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		normalStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
		normalStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
		normalStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		normalStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		normalStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
		normalStyle.setWrapText(true);

		// 1 写入excle的header
		formater.renderHeader(wb, st, normalStyle);

		// 2 填写数据
		formater.renderDatas(wb, st, normalStyle, list);

		return wb;
	}

	private List<CriminalBase> search(Condition condition) {
		// TODO Auto-generated method stub
		try {
			return forTest();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * For：测试使用
	 * 
	 * @throws Exception
	 * */
	private List<CriminalBase> forTest() throws Exception {
		List<CriminalBase> list = new ArrayList<CriminalBase>();
		CriminalBase cb = (CriminalBase) create(CriminalBase.class);
		System.out.println(cb);
		list.add(cb);

		return list;
	}

	private String space = "";

	private Object create(Class cls) throws Exception {
		// System.out.println(cls.getSimpleName());
		Object ins = cls.newInstance();
		Field[] fields = cls.getDeclaredFields();
		for (Field field : fields) {
			// static final
			int m = field.getModifiers();
			if (Modifier.isStatic(m)) {
				continue;
			}

			String type = field.getType().getSimpleName();

			Object obj = getValue(field);
			field.setAccessible(true);
			field.set(ins, obj);
		}
		return ins;
	}

	private Object getValue(Field field) throws Exception {

		String type = field.getType().getSimpleName();
		String attrName = field.getName();
		Class typeClass = field.getType();
		// System.out.println("  "+typeClass+" "+attrName);
		Object obj;
		// [CivilDispute, String, CriminalMember, RobSteal, Integer, long]
		if ("String".equals(type)) {
			obj = ">" + attrName;
		} else if ("Integer".equals(type) || "int".equals(type) || "long".equals(type) || "Long".equals(type)
				|| "double".equals(type) || "Double".equals(type)) {
			obj = 1;

		} else if ("CivilDispute".equals(type) || "CriminalMember".equals(type) || "RobSteal".equals(type)
				|| "Religion".equals(type)) {
			obj = create(typeClass);
		} else {
			// throw new Exception("Error : "+
			// field.getType().getName()+"  类型没有实现！！！ 请重写代码，并实现。");
			return null;
		}
		return obj;

	}

	private static void printAttr(Class cls) {
		Field[] fields = cls.getDeclaredFields();
		System.out.println("Class::::::::" + cls.getName());
		for (Field field : fields) {
			// static final
			int m = field.getModifiers();
			if (Modifier.isStatic(m)) {
				continue;
			}

			System.out.println(field.getName());
		}
	}

	public static void main(String[] args) throws IOException, IllegalArgumentException, IllegalAccessException {
		ExportExcelController eec = new ExportExcelController();
		List<CriminalBase> list = eec.search(new Condition());

		HSSFWorkbook wb = eec.createWorkbook(list);
		OutputStream out = new FileOutputStream("G:/test.xls");
		wb.write(out);
		// printAttr(CriminalBase.class);
	}
}
